package org.entities;

import org.GameState;
import org.newdawn.slick.Graphics;

public class Tank extends Entity {

	float dx = 0;
	float dy = 0;
	
	float rotation = 0;
	int targetRotation = -1;
	
	float topSpeed = 0.2f;
	float speed = 0;
	
	float turnSpeed = 0.15f;
	
	float acceleration = 0.001f;
	float resistance = 0.0005f;
	
	public Tank(GameState game, int x, int y) {
		super(game, x, y, 20, 20);
		//bounds.setX(x-10);
		//bounds.setY(y-10);
	}
	
	public void targetRotation(int angle) {
		targetRotation = angle;
	}
	
	public float getX() {
		return x;
	}
	
	public float getY() {
		return y;
	}
	
	public void update(int delta) {
		
		if (targetRotation != -1) {
			
			if (targetRotation - rotation > 180) targetRotation -= 360;
			else if (rotation - targetRotation > 180) targetRotation += 360;
			
			if (rotation < targetRotation) {
				rotation += turnSpeed * delta;
				if (rotation > targetRotation) rotation = targetRotation;
			}
			else if (rotation > targetRotation) {
				rotation -= turnSpeed * delta;
				if (rotation < targetRotation) rotation = targetRotation;
			}
			
			if (rotation >= 360) rotation -= 360;
			if (rotation < 0) rotation += 360;
			
			// reset targetRotation
			targetRotation = -1;
			
			// calculate the vector from angle
			dx = (float)(Math.cos(Math.toRadians(rotation - 90)));
			dy = (float)(Math.sin(Math.toRadians(rotation - 90)));
			
			speed += acceleration * delta;
			
			if (speed > topSpeed) {
				speed = topSpeed;
			}
		}
		else {
			speed -= resistance * delta;
			if (speed < 0) speed = 0;
		}
		
		if (speed != 0) {
			
			float ax = dx * speed * delta;
			float ay = dy * speed * delta;
			
			if (ax != 0) {
				x += ax;
				bounds.setX(x-10);
				if (game.collisionDetection(this)) {
					x -= ax;
					bounds.setX(x-10);
				}	
			}
			
			if (ay != 0) {
				y += ay;
				bounds.setY(y-10);
				if (game.collisionDetection(this)) {
					y -= ay;
					bounds.setY(y-10);
				}
			}
			
			if (x < 48) x = 48;
			if (y < 48) y = 48;
			
			if (x > game.mapWidth - 48) x = game.mapWidth - 48;
			if (y > game.mapHeight - 48) y = game.mapHeight - 48;
			
			//bounds.setX(x - 10);
			//bounds.setY(y - 10);
		}
	}
	
	public void draw(Graphics g) {
		game.tankBaseImage.setRotation(rotation);
		
		game.tankBaseImage.draw(x - game.tankBaseImage.getWidth()/2, y - game.tankBaseImage.getHeight()/2);
		game.tankTurretImage.draw(x - game.tankTurretImage.getWidth()/2, y - game.tankTurretImage.getHeight()/2);
		
		g.draw(bounds);
	}
	
	public boolean isCollisionWith(Entity other) {
		return bounds.intersects(other.bounds);
	}
	
	public boolean collidedWith(Entity entity) {
		return true;
	}
}
